package com.xinghai.wechat;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xinghai.common.utils.http.HttpUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class WeChatService {

    private static final String APP_ID = "wx70d2645a294cedfc";  // 你的 APP ID
    private static final String APP_SECRET = "607d4588a2fd8237c3bdc906a269a9b4";  // 你的 APP SECRET

    public static String getOpenId(String code) throws IOException {
        // 构建请求 URL
        String url = "https://api.weixin.qq.com/sns/jscode2session" +
        "appid=" + APP_ID +
                "&secret=" + APP_SECRET +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        // 发起 GET 请求
        URL object = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) object.openConnection();
        connection.setRequestMethod("GET");

        // 获取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        // 关闭资源
        reader.close();
        connection.disconnect();

        return response.toString();  // 返回结果，包含 openid 和 session_key
    }
}
